import React, { useEffect, useState, useRef } from 'react';
import {
  Box,
  Card,
  CardContent,
  Typography,
  Grid,
  CircularProgress,
  Alert,
  Tooltip,
  LinearProgress,
  Chip,
} from '@mui/material';
import { useTheme } from '@mui/material/styles';
import { green, red, orange } from '@mui/material/colors';

export default function Data() {
  const [properties, setProperties] = useState({});
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [trends, setTrends] = useState({});
  const theme = useTheme();
  const historicalData = useRef({});

  const keyMap = {
    temperature: '温度',
    humidity: '湿度',
    pressure: '气压',
    pm25: 'PM2.5',
    illumination: '光照强度',
    smoke: '可燃气体',
  };

  const fetchData = () => {
    fetch('http://localhost:8088/device/shadow')
      .then(res => {
        if (!res.ok) throw new Error('网络请求失败');
        return res.json();
      })
      .then(json => {
        const props = json.properties?.Properties || {};
        updateTrends(props);
        setProperties(props);
        setLoading(false);
        setError(null);
      })
      .catch(err => {
        console.error('获取设备属性失败:', err);
        setError(err.message);
        setLoading(false);
      });
  };

  const updateTrends = (newData) => {
    const newTrends = {};
    Object.entries(newData).forEach(([key, value]) => {
      const currentValue = parseFloat(value);
      if (isNaN(currentValue)) return;

      if (historicalData.current[key] !== undefined) {
        const prevValue = historicalData.current[key];
        if (currentValue > prevValue) newTrends[key] = 'up';
        else if (currentValue < prevValue) newTrends[key] = 'down';
        else newTrends[key] = 'stable';
      }
      historicalData.current[key] = currentValue;
    });
    setTrends(newTrends);
  };

  useEffect(() => {
    fetchData();
    const intervalId = setInterval(fetchData, 5000);
    return () => clearInterval(intervalId);
  }, []);

  const getTrendIcon = (key) => {
    switch (trends[key]) {
      case 'up':
        return <Chip label="↑" color="success" size="small" />;
      case 'down':
        return <Chip label="↓" color="error" size="small" />;
      case 'stable':
        return <Chip label="→" color="primary" size="small" />;
      default:
        return null;
    }
  };

  const getDataCardColor = (key) => {
    if (key.includes('battery')) {
      const value = parseFloat(properties[key] || 0);
      if (value < 20) return red[500];
      if (value < 50) return orange[500];
      return green[500];
    }
    return theme.palette.primary.main;
  };

  const getLabel = (key) => keyMap[key] || key;

  if (loading) {
    return (
      <Card sx={{ p: 3, mt: 2, bgcolor: '#fdf6f9' }}>
        <CardContent>
          <Box display="flex" alignItems="center" justifyContent="center" py={5}>
            <CircularProgress color="primary" />
            <Typography ml={2} color="#ff69b4">加载传感器数据中...</Typography>
          </Box>
        </CardContent>
      </Card>
    );
  }

  if (error) {
    return (
      <Card sx={{ p: 3, mt: 2, bgcolor: '#fdf6f9' }}>
        <CardContent>
          <Alert severity="error">{`传感器数据获取失败: ${error}`}</Alert>
        </CardContent>
      </Card>
    );
  }

  return (
    <Card
      elevation={3}
      sx={{
        p: 3,
        mt: 1.5,
        bgcolor: '#fdf6f9',
        borderRadius: 4,
        height: '80%',
        minHeight: 260,
        maxHeight: 420,
      }}
    >
      <CardContent>

        <Box display="flex" alignItems="center" justifyContent="space-between" mb={3}>
          <Typography variant="h5" sx={{ fontWeight: 'bold', color: '#ff69b4' }}>
            📊 传感器实时数据
          </Typography>
          {/* <Tooltip title="数据每5秒自动更新">
            <Chip
              label={`最后更新: ${new Date().toLocaleTimeString()}`}
              variant="outlined"
              size="small"
              sx={{ color: '#ff69b4' }}
            />
          </Tooltip> */}
        </Box>

        <Box sx={{ width: '100%', height: '100%' }}>
          <Grid container spacing={2} alignItems="stretch" justifyContent="stretch" wrap="nowrap" sx={{ width: '100%', height: '100%' }}>
            {Object.entries(properties).map(([key, value]) => (
              <Grid
                item
                key={key}
                xs={true}
                sm={true}
                md={true}
                lg={true}
                xl={true}
                sx={{ flex: 1, display: 'flex', flexDirection: 'column', height: '100%' }}
              >
                <Card
                  elevation={2}
                  sx={{
                    width: '100%',
                    height: '100%',
                    minHeight: 140,
                    bgcolor: '#fff0f5',
                    border: '1px solid #ffd6e8',
                    transition: 'transform 0.3s',
                    '&:hover': { transform: 'translateY(-3px)' },
                    display: 'flex',
                    flexDirection: 'column',
                    justifyContent: 'center',
                  }}
                >
                  <CardContent sx={{ p: 1 }}>
                    <Box display="flex" justifyContent="space-between" alignItems="center" mb={0.5}>
                      <Typography variant="subtitle2" fontWeight="bold" color="#555" noWrap>
                        {getLabel(key)}
                      </Typography>
                      {getTrendIcon(key)}
                    </Box>

                    <Box display="flex" alignItems="center" justifyContent="space-between">
                      <Typography variant="h6" color={getDataCardColor(key)}>
                        {value}
                      </Typography>

                      {key.includes('battery') && (
                        <Box width="40%">
                          <LinearProgress
                            variant="determinate"
                            value={parseFloat(value) || 0}
                            color={getDataCardColor(key)}
                            sx={{ height: 8, borderRadius: 5 }}
                          />
                        </Box>
                      )}
                    </Box>
                  </CardContent>
                </Card>
              </Grid>
            ))}
          </Grid>
        </Box>
      </CardContent>
    </Card>
  );
}
